package com.example.pet.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pet.entity.Consult;
import com.example.pet.service.ConsultService;
import com.example.pet.util.Response;
import com.example.pet.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/consult")
public class ConsultController {

    @Autowired
    private ConsultService consultService;

    @RequestMapping("")
    public String consult(Model model,Page<Consult> page, String title) {
        page.setSize(5);
        QueryWrapper<Consult> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Consult::getUpdateTime);
        queryWrapper.lambda().eq(Consult::getUserId, SessionUtil.getUserId());
        if (StringUtils.hasLength(title)) {
            queryWrapper.lambda().like(Consult::getTitle,title);
        }
        IPage<Consult> iPage = consultService.page(page,queryWrapper);
        iPage.getRecords().forEach(x->x.setContent(x.getContent().replace("\\n","")));
        model.addAttribute("data",iPage);
        return "consult";
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public Response delete(@PathVariable Integer id) {
        return Response.result(consultService.removeById(id));
    }

    @PostMapping("/save")
    @ResponseBody
    public Response delete(Consult consult) {
        consult.setUserId(SessionUtil.getUserId());
        return Response.result(consultService.saveOrUpdate(consult));
    }

}
